<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends EXT_Controller
{

	function __construct()
	{
		parent::__construct();
		$this->lang->load('user');
		$this->load->model('user_model');
	}

	function login()
	{
		if($this->user_model->loggedIn())
		{
			redirect(siteUrl('admin'), 'refresh');
		}

		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', 'lang:username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'lang:password', 'trim|required|xss_clean|callback_login_check');
		
		if($this->form_validation->run() == FALSE)
		{
			$this->messages->add(validation_errors(), 'e');
			$this->output->set_title(lang('login'));
			$this->output->set_template('panel');
			$this->load->view('frontend/user/login');
		}
		else
		{
			redirect(siteUrl('admin'), 'refresh');
		}
	
	}
	public function logout()
	{
		$this->user_model->logout();
		redirect('user/login', 'refresh');
	}

	function login_check($password)
	{
		$username = $this->input->post('username');
		$remember = intval($this->input->post('remember'));

		$this->user_model->item_where = array(
			'username'=>$username,
			'password'=>$password,
		);
		if(!$this->user_model->login($username, $password, $remember))
		{
			$this->form_validation->set_message('login_check', lang('invalid_username_or_password'));
			return false;
		}
		return true;
	}
}
